import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { delAction, setAll as setAllAction, updateAction } from './../store/action/todo';

export default function Main() {
  // 4. 按具体功能模块获取数据
  const { list, type } = useSelector((state) => state.todo);

  const showList = list.filter((item) => {
    if (type === 'active') return !item.isDone;
    if (type === 'completed') return item.isDone;
    return true;
  });

  const isAll = list.length ? list.every((item) => item.isDone) : false;
  const dispatch = useDispatch();

  return (
    <section className="main">
      <input
        onChange={(e) => {
          dispatch(setAllAction(e.target.checked));
        }}
        checked={isAll}
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
      />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {showList.map((item) => {
          return (
            <li key={item.id} className={item.isDone ? 'completed' : ''}>
              <div className="view">
                <input
                  onChange={() => dispatch(updateAction(item.id))}
                  checked={item.isDone}
                  className="toggle"
                  type="checkbox"
                />
                <label>{item.task}</label>
                <button onClick={() => dispatch(delAction(item.id))} className="destroy"></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
